package utils

import "encoding/base64"

func Base64Decode(str string) ([]byte, error) {
	strBuf := []byte(str)
	l := len(str)
	if l%4 == 0 {
		enc := base64.StdEncoding
		dbuf := make([]byte, enc.DecodedLen(l))
		n, err := enc.Decode(dbuf, strBuf)
		return dbuf[:n], err
	} else {
		enc := base64.RawStdEncoding
		dbuf := make([]byte, enc.DecodedLen(l))
		n, err := enc.Decode(dbuf, strBuf)
		return dbuf[:n], err
	}
}

func Base64EncodeFromFile(filename string) string {
	fileData, err := ReadFile(filename)
	if err != nil {
		return ""
	}
	return base64.StdEncoding.EncodeToString(fileData)
}

func Base64Decode2File(str string, filename string) error {
	buf, err := Base64Decode(str)
	if err != nil {
		return err
	}

	return RewriteFile(filename, buf)
}
